import path from "path";
import fs from 'fs'
import fse  from 'fs-extra'
// 0. 加载 Express
import express from 'express'
import multer from 'multer' // 文件上传
import { mergeFile, deleteFolderRecursive } from './utils.js'
// var storage = multer.diskStorage({

//   destination: function (req, file, cb) {
//     console.dir(req)
//     cb(null, path.resolve('upload', req.body.hash))
//   },

//   filename: function (req, file, cb) {
//     console.log(file)
//     cb(null, file.fieldname)
//   }
//  })

const upload = multer({dest:'upload/'}) 
//  var upload = multer({ storage: storage })

// 1. 调用 express() 得到一个 app
//    类似于 http.createServer()
const app = express()
app.use((req,res,next)=>{
  console.log(req.url)
  next()
})
app.use(express.json());
app.post('/checkfile', async (req,res) => {
  const { ext, hash } = req.body
  const filePath = path.resolve('upload', `${hash}.${ext}`)

  let uploaded = false
  let uploadedList  = []
  if (fs.existsSync(filePath)) {
    // 文件存在
    uploaded = true
  } else {
    uploadedList = await getUploadedList(path.resolve('upload', hash))
  }
  res.send({
    uploaded,
    uploadedList,
  })
})

// .DS_Strore
function getUploadedList(dirPath) {
  return fs.existsSync(dirPath)
    ? (fs.readdirSync(dirPath)).filter(name => name[0] !== '.')
    : []
}
app.post('/uploadfile', upload.single('chunk'), async (req, res) => {
  const file = req.file
  const { hash, name } = req.body

  const chunkPath = path.resolve('upload', hash)
  // const filePath = path.resolve() // 文件最终存储的位置。合并之后

  // console.log(name,file)

  // console.log(file.filepath)
  // console.log(this.config.UPLOAD_DIR)
  if (!fs.existsSync(chunkPath)) {
    fs.mkdirSync(chunkPath)
  }

  await fse.move(file.path, `${chunkPath}/${name}`)
  

  res.send({
    file: file,
    message: 'ok',
    hash, name
  })
})

app.post('/mergefile', async (req, res) => {
  const { ext, size, hash } = req.body
  // const filePath = path.resolve('upload', `${hash}.${ext}`)
  await mergeFile(hash,ext)
  deleteFolderRecursive(path.resolve('upload', `${hash}`))
  res.send({
    message: 'ok'
  })
})

// 3. 监听端口号，启动 Web 服务
app.listen(3000, () => console.log('app listening on port 3000!'))